package com.shwread.android.qysw.activity.psychological;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.NewActionHelp;
import com.google.gson.reflect.TypeToken;
import com.shwread.android.qysw.bean.psychological.AccountPwdInfo;
import com.shwread.android.qysw.bean.psychological.EvaluatingDetailBean;
import com.shwread.http.base.ObjectHttpResponseHandler;
import com.shwread.http.base.TextHttpResponseHandler;
import com.ui.dialog.CustomDialog;

import org.apache.http.Header;

import java.lang.reflect.Type;

import logic.pay.PayResult;
import logic.pay.PayUtil;
import logic.util.Utils;

/**
 * 心理评测支付工具类
 * Created by sss on 2017/10/16.
 */
public class EvaluatingPayUtils {
    private Activity activity;
    private Listener listener;
    private String mOrderNo;
    private EvaluatingDetailBean evaluatingDetailBean;
    private ProgressDialog dialog;

    public static EvaluatingPayUtils getInstance() {
        return new EvaluatingPayUtils();
    }

    public void pay(Activity activity, EvaluatingDetailBean evaluatingDetailBean, Listener listener) {
        this.activity = activity;
        this.listener = listener;
        this.evaluatingDetailBean = evaluatingDetailBean;
        NewActionHelp.createQuestionnaireOrder(activity, evaluatingDetailBean.getQuestionnaireId(), new CreateQuestionnaireOrderHandler());
    }

    private class CreateQuestionnaireOrderHandler extends ObjectHttpResponseHandler<String> {

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            Log.e("sss", "失败---" + responseString);
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, String orderNo, String responseString) {
            Log.e("sss", "成功---" + responseString);
            if (TextUtils.isEmpty(orderNo)) {
                new CustomDialog.Builder(activity)
                        .setMessage("评测登录账户开了点小差，请稍后重试")
                        .setNegativeButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).create().show();
                return;
            }
            //调用支付宝支付
            final String orderInfo = PayUtil.getOrderInfo(orderNo, evaluatingDetailBean.getTitle(), evaluatingDetailBean.getTitle(), String.valueOf(evaluatingDetailBean.getPrice()));
            mOrderNo = orderNo;
            PayUtil.pay(activity, handler, orderInfo);
        }

        @Override
        public Type getType() {
            return new TypeToken<String>() {
            }.getType();
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case PayUtil.SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);
                    // 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
                    String resultStatus = payResult.getResultStatus();
                    switch (resultStatus) {
                        case "9000"://支付成功
                            dialog = new ProgressDialog(activity);
                            dialog.setCancelable(false);
                            dialog.setCanceledOnTouchOutside(false);
                            dialog.setTitle("请稍候...");
                            dialog.show();
                            NewActionHelp.receiveClientNotify(activity, mOrderNo, new TextHttpResponseHandler() {
                                @Override
                                public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                                    Utils.showToast(activity, "支付失败");
                                    if (dialog != null) {
                                        dialog.dismiss();
                                    }
                                }

                                @Override
                                public void onSuccess(int i, Header[] headers, String s) {
                                    NewActionHelp.judgeBuyTimes(activity, mOrderNo, new JudgeBuyTimesHandler());
                                }
                            });
                            break;
                        case "8000"://支付结果确认中
                            // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                            Utils.showToast(activity, "支付结果确认中");
                            break;
                        case "6001"://取消支付
                            Utils.showToast(activity, "购买失败");
//                            NewActionHelp.judgeBuyTimes(activity, mOrderNo, new JudgeBuyTimesHandler());
                            break;
                        default:
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            Utils.showToast(activity, "购买失败");
                            break;
                    }
                    break;
                }
                case PayUtil.SDK_CHECK_FLAG: {
                    Utils.showToast(activity, "是否有支付宝认证账号：" + msg.obj);
                    break;
                }
            }
        }
    };

    private class JudgeBuyTimesHandler extends ObjectHttpResponseHandler<AccountPwdInfo> {
        @Override
        public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
            new CustomDialog.Builder(activity)
                    .setMessage("评测登录账户开了点小差，请稍后重试")
                    .setNegativeButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).create().show();
            if (dialog != null) {
                dialog.dismiss();
            }
        }

        @Override
        public void onSuccess(int i, Header[] headers, final AccountPwdInfo accountPwdInfo, String s) {
            if (TextUtils.isEmpty(accountPwdInfo.getAccount()) || TextUtils.isEmpty(accountPwdInfo.getPassword())) {
                new CustomDialog.Builder(activity)
                        .setMessage("评测登录账户开了点小差，请稍后重试")
                        .setNegativeButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).create().show();
                return;
            }
            Utils.showToast(activity, "支付成功");
            listener.CallBack();//成功回调
            if (dialog != null) {
                dialog.dismiss();
            }
            if (accountPwdInfo.getStatus() == 0) {//未绑定
                new AccountPasswordDialog()
                        .setOnClickListener(new AccountPasswordDialog.ClickListener() {
                            @Override
                            public void onClick(String msgPhone) {
                                //发送短信
                                NewActionHelp.smsPushQuestionnaireAccount(activity, accountPwdInfo.getAccount(), accountPwdInfo.getPassword(), msgPhone, new SmsPushHandler());
                            }
                        })
                        .setCancel(false)
                        .show(activity, "sss");
            } else {
                new AccountPasswordDialog().setContent(accountPwdInfo.getAccount(), accountPwdInfo.getPassword()).setCancel(false).show(activity, "sss");
            }
        }

        @Override
        public Type getType() {
            return new TypeToken<AccountPwdInfo>() {
            }.getType();
        }
    }

    private class SmsPushHandler extends ObjectHttpResponseHandler<String> {
        @Override
        public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
            Utils.showToast(activity, "发送失败");
        }

        @Override
        public void onSuccess(int i, Header[] headers, String s, String s2) {
            Utils.showToast(activity, "发送成功");
        }

        @Override
        public Type getType() {
            return new TypeToken<String>() {
            }.getType();
        }
    }

    public interface Listener {
        void CallBack();
    }
}
